package com.meviewer.common;

import android.util.Log;

import com.google.common.base.Stopwatch;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author hanhaoran
 * HTTP连接池 可以同步/异步执行
 */
public final class Http {
    private Http() {}

    private static OkHttpClient INSTANCE;

    public static Response sync(Request request) {
        ensureHttpClientReady();
        try {
            return INSTANCE.newCall(request).execute();
        } catch (IOException e) {
            return null;
        }
    }

    public static void async(Request request, Callback callback) {
        ensureHttpClientReady();
        INSTANCE.newCall(request).enqueue(callback);
    }

    private static synchronized void ensureHttpClientReady() {
        if (Objects.isNull(INSTANCE)) {
            init();
        }
    }

    private static synchronized void init() {
        Stopwatch stopwatch = Stopwatch.createStarted();
        INSTANCE = new OkHttpClient.Builder()
                .connectionPool(
                        new ConnectionPool(
                                Runtime.getRuntime().availableProcessors(),
                                Constants.INT32,
                                TimeUnit.SECONDS
                        )
                ).connectTimeout(Constants.ONE, TimeUnit.SECONDS)
                .readTimeout(Constants.ONE, TimeUnit.SECONDS)
                .writeTimeout(Constants.ONE, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false)
                .build();
        stopwatch.stop();
        Log.i(Http.class.getName(), String.format("Http client init success with %s ms", stopwatch.elapsed(TimeUnit.MILLISECONDS)));
    }
}
